#include "Temperature_logger.h"


void ADC_init(char input)
{
	ADMUX=input;
	ADCSRA=(1<<ADEN)|(1<<ADPS1)|(1<<ADPS0);
	input=ADC_read();
}

int ADC_read(void)
{
	char i;
	int ADC_temp;
	int ADCr = 0;

	sbi(PORTF, PF3); 
	sbi(DDRF, DDF3);
	sbi(ADCSRA, ADEN); 
	ADCSRA |= (1<<ADSC); 
	while(!(ADCSRA & 0x10));

	for(i=0;i<8;i++)
	{
	ADCSRA |= (1<<ADSC); 
	while(!(ADCSRA & 0x01));
	ADC_temp = ADCL; 
	ADC_temp += (ADCH << 8); 
	ADCr += ADC_temp;
	}

	ADCr = ADCr >> 3; 
	cbi(PORTF,PF3); 
	cbi(DDRF,DDF3); 
	cbi(ADCSRA, ADEN); 

	return ADCr;
}

int getLight(void)
{
	int ADCresult=0;
	ADC_init(2);
	ADCresult = ADC_read();
	return ADCresult;

}


char getTemperature(void)
{

//const int TEMP_Fahrenheit_pos[141] PROGMEM=
/*const int TEMP_Fahrenheit_pos[141] =
{
938, 935, 932, 929, 926, 923, 920, 916, 913, 909, 906, 902,
898, 894, 891, 887, 882, 878, 874, 870, 865, 861, 856, 851,
847, 842, 837, 832, 827, 822, 816, 811, 806, 800, 795, 789,
783, 778, 772, 766, 760, 754, 748, 742, 735, 729, 723, 716,
710, 703, 697, 690, 684, 677, 670, 663, 657, 650, 643, 636,
629, 622, 616, 609, 602, 595, 588, 581, 574, 567, 560, 553,
546, 539, 533, 526, 519, 512, 505, 498, 492, 485, 478, 472,
465, 459, 452, 446, 439, 433, 426, 420, 414, 408, 402, 396,
390, 384, 378, 372, 366, 360, 355, 349, 344, 338, 333, 327,
322, 317, 312, 307, 302, 297, 292, 287, 282, 277, 273, 268,
264, 259, 255, 251, 246, 242, 238, 234, 230, 226, 222, 219,
215, 211, 207, 204, 200, 197, 194, 190, 187,
};
*/
//REDUCED RANGE TO SAVE SPACE!!!!
const int TEMP_Fahrenheit_pos[72] =
{
847, 842, 837, 832, 827, 822, 816, 811, 806, 800, 795, 789,
783, 778, 772, 766, 760, 754, 748, 742, 735, 729, 723, 716,
710, 703, 697, 690, 684, 677, 670, 663, 657, 650, 643, 636,
629, 622, 616, 609, 602, 595, 588, 581, 574, 567, 560, 553,
546, 539, 533, 526, 519, 512, 505, 498, 492, 485, 478, 472,
465, 459, 452, 446, 439, 433, 426, 420, 414, 408, 402, 396,
};

	int ADCresult = 0;
	int i = 0;
	float Temp_Cel=0.0;
	ADC_init(0); 
	ADMUX = 0; 
	ADCresult = ADC_read();
	for (i=0;i<=71;i++)
	{
		if(ADCresult>(TEMP_Fahrenheit_pos[i]))
		{
			break;
		}
	}
	Temp_Cel=(((i+24)-32)/1.8);
	return ((char)Temp_Cel);
}